package com.masterclient.app.businessmodule.homemodule.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.eoner.commonbean.banner.BannerNewItemBean;
import com.masterclient.app.businessmodule.homemodule.bean.banner.BannerNewBean;
import com.masterclient.app.businessmodule.homemodule.bean.banner.SpecialImagBean;
import com.masterclient.app.businessmodule.homemodule.bean.footertab.HomeFooterTabData;
import com.masterclient.app.businessmodule.homemodule.bean.homecms.HomeNewCmsIndexBean;
import com.masterclient.app.businessmodule.homemodule.bean.shoplist.ProductHomeMessage;
import com.eoner.managerlibrary.version.VersionManager;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.homemodule.bean.footertab.HomeFooterTabBean;
import com.masterclient.app.businessmodule.homemodule.bean.homecms.HomeCmsIndexBean;
import com.masterclient.app.businessmodule.homemodule.bean.hot.HotSearchWordBean;
import com.masterclient.app.businessmodule.homemodule.bean.saletabs.FlashSaleTabBean;
import com.masterclient.app.businessmodule.homemodule.presenter.IHomePresenter;
import com.masterclient.app.businessmodule.homemodule.view.adapter.HomeRecycleAdapterGroup;
import com.masterclient.app.businessmodule.homemodule.view.adapter.top.HomeTopComponent;
import com.masterclient.app.businessmodule.homemodule.view.footer.HomeClassicFooter;
import com.masterclient.app.businessmodule.homemodule.view.helper.HomeMainViewHelper;
import com.masterclient.app.businessmodule.homemodule.view.listenerimpl.HomeViewEventListenerImpl;
import com.eoner.uikit.header.MyRefreshHead;
import com.masterclient.app.widget.MaterialBadgeTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.List;

import static com.eoner.uikit.header.MyRefreshHead.LOTTIE;

public class HomeMainView extends FrameLayout implements IHomeMainView {

    private IHomePresenter iHomePresenter;

    //UI
    private View rl_msg;
    private MaterialBadgeTextView ivUnread;
    //刷新控件
    private SmartRefreshLayout mRefreshLayout;
    private MyRefreshHead myRefreshHead;
    //滑动到顶部的控制view
    private ImageView mBackTopView;
    //列表试图
    private RecyclerView mRecyclerView;
    //toolbar
//    private Toolbar mToolBar;
    //顶部组件
    private HomeTopComponent mHomeTopComponent;
    //helper (辅助类)
    private HomeMainViewHelper mViewHelper;
    //adapter group
    private HomeRecycleAdapterGroup mAdapterGroup;
    //事件监听
    private HomeViewEventListenerImpl mHomeViewEventListenerImpl;

    //error
    private LinearLayout mErrorView;
    //顶部标题
    private View mTitleView;

    private boolean isFirstLoadMore = false;

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                     初始化工作
    //
    /////////////////////////////////////////////////////////////////////////////////

    public HomeMainView(@NonNull Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.layout_new_home_main,this);
        initUI();
    }

    public HomeMainView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_new_home_main,this);
        initUI();
    }

    @Override
    public IHomeMainView bindPresenterAndInteraction(IHomePresenter iHomePresenter) {
        this.mHomeViewEventListenerImpl = new HomeViewEventListenerImpl().bindPresenterAndInteraction(iHomePresenter,this);
        this.iHomePresenter = iHomePresenter;
        return this;
    }

    private void initUI() {
        rl_msg = findViewById(R.id.rl_msg);
        ivUnread = findViewById(R.id.iv_unread);
        mTitleView = findViewById(R.id.view_title);
        mErrorView = findViewById(R.id.home_error_view);
        mBackTopView = findViewById(R.id.home_iv_back_top);
        mRecyclerView = findViewById(R.id.home_recycler);
//        mToolBar = findViewById(R.id.home_toolbar);
        mHomeTopComponent = findViewById(R.id.home_top_component);
        mRefreshLayout = findViewById(R.id.home_swipeLayout);
        myRefreshHead = new MyRefreshHead(getContext(), 1, LOTTIE);
        myRefreshHead.changeBackColor(Color.parseColor("#F23051"));
        myRefreshHead.changeTextColor(Color.parseColor("#FFFFFF"));
        mRefreshLayout.setRefreshHeader(myRefreshHead);
        mRefreshLayout.setRefreshFooter(new HomeClassicFooter(getContext()));
    }

    @Override
    public void initMainView(int statusBarHeight) {
        //top
        mHomeTopComponent.setHomeTopComponentListener(mHomeViewEventListenerImpl);
        //helper
        mViewHelper = new HomeMainViewHelper(statusBarHeight,this);
        mViewHelper.setRecycleListener();
        mViewHelper.setRefreshLayoutListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                if (mAdapterGroup != null) {
                    mAdapterGroup.destroyTimer();
                }
                //检测版本更新
                VersionManager.getInstance()
                        .setActivity((Activity) getContext())
                        .checkVersionUpdate(true);
                if (iHomePresenter != null) {
                    //刷新头部信息
                    iHomePresenter.serviceApiHomeData();
                }
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                if (iHomePresenter != null) {
                    iHomePresenter.serviceFooterNewShopDataLoadMore(-1,isFirstLoadMore);
                    isFirstLoadMore = true;
                }
            }
        });

        //消息点击
        rl_msg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (iHomePresenter != null) {
                    iHomePresenter.interactionToOpenMessagePage();
                }
            }
        });
        //back top

        mBackTopView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        mViewHelper.setDistanceY(0);
                        mRecyclerView.scrollToPosition(0);
                    }
                });
            }
        });
        //adapter
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getContext());
        layoutManager.setInitialPrefetchItemCount(10);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setItemViewCacheSize(16);
        mAdapterGroup = new HomeRecycleAdapterGroup(layoutManager, false);
        mAdapterGroup.setHomeRecycleAdapterGroupListener(mHomeViewEventListenerImpl);
        mRecyclerView.setAdapter(mAdapterGroup);
        //error
        mErrorView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mErrorView.setVisibility(GONE);
                if (iHomePresenter != null) {
                    iHomePresenter.serviceApiHomeData();
                }
            }
        });
    }


    /////////////////////////////////////////////////////////////////////////////////
    //
    //                    试图获取
    //
    /////////////////////////////////////////////////////////////////////////////////


    @Override
    public HomeMainViewHelper viewHelper() {
        return mViewHelper;
    }

    @Override
    public Toolbar mainToolBar() {
        return null;
    }

    @Override
    public View mainTitleView() {
        return mTitleView;
    }

    @Override
    public SmartRefreshLayout refreshLayout() {
        return mRefreshLayout;
    }

    @Override
    public RecyclerView recyclerView() {
        return mRecyclerView;
    }

    @Override
    public MyRefreshHead myRefreshHead() {
        return myRefreshHead;
    }

    @Override
    public HomeTopComponent homeTopComponent() {
        return mHomeTopComponent;
    }

    @Override
    public TextView currentSearchTextView() {
        if (mHomeTopComponent != null) {
            return mHomeTopComponent.getSearchTextView();
        }
        return null;
    }

    @Override
    public ImageView backTopView() {
        return mBackTopView;
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                    页面基本刷新
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 刷新状态
     * isSuccess 成功/失败
     * */
    @Override
    public void finishRefresh(boolean isSuccess) {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishRefresh(isSuccess);
        }
    }

    @Override
    public void showErrorView() {
        mErrorView.setVisibility(VISIBLE);
    }

    @Override
    public void finishLoadMore() {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishLoadMore();
        }
    }

    @Override
    public void noMoreData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void resetNoMoreData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.resetNoMoreData();
        }
    }

    /**
     * 根据透明度改变顶部组件
     * */
    @Override
    public void refreshTopStateByAlpha(float alphaFloat) {
        if (mHomeTopComponent != null) {
//            mHomeTopComponent.refreshTopStateByAlpha(alphaFloat);
        }
    }

    @Override
    public void setFooterTabState(int state) {
        if (mAdapterGroup != null) {
            mAdapterGroup.setFooterTabState(state);
        }
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                   首页接口数据加载渲染
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 重置首页列表先显示
     * */
    @Override
    public void refreshHomeDataToResetListState() {
        if (mViewHelper != null) {
            mViewHelper.setFooterStickPosition(0);
        }
        mAdapterGroup.clearAdapters();
        mRecyclerView.setAdapter(mAdapterGroup);
    }

    /**
     * 刷新顶部搜索栏
     * keyword 搜索词
     * isAnimation 是否加动画
     * */
    @Override
    public void refreshHomeDataToTopSearchView(String keyword,boolean isAnimation) {
        if (mHomeTopComponent != null) {
            mHomeTopComponent.refreshTopSearchView(keyword,false);
        }
    }

    /**
     * 刷新消息红点
     * */
    @Override
    public void refreshHomeDataToRedImageState(boolean isHidden,String noticeNum) {
        if (isHidden) {
            ivUnread.setVisibility(INVISIBLE);
        } else {
            ivUnread.setBadgeCount(noticeNum);
            ivUnread.setVisibility(VISIBLE);
        }
    }

    /**
     * 刷新banner和热词
     * */
    @Override
    public void refreshHomeDataToBannerAndHot(List<HotSearchWordBean> hotSearchWordBeanList, BannerNewBean bannerBean) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToAddBannerAdapter(getContext(),hotSearchWordBeanList,bannerBean);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshSignData(String imgUrl) {
        if (mHomeTopComponent != null) {
            mHomeTopComponent.refreshSignData(imgUrl);
        }
    }

    @Override
    public void refreshHomeDataToFeature(BannerNewBean bannerBean) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToAddFeatureAdapter(getContext(),bannerBean);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToTwoPic(SpecialImagBean diamonds) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToAddTowPicAdapter(getContext(),diamonds);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToDiamonds(BannerNewBean diamonds) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToAddDiamondsAdapter(getContext(),diamonds);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToCapsules(List<BannerNewItemBean> capsules) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToAddCapsulesAdapter(getContext(),capsules);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToPromotionsAndGradual(BannerNewBean promotions) {
        if (mAdapterGroup != null) {
            //大促
            boolean isPromoteSuccess = mAdapterGroup.homeDataToAddPromotionsAdapter(getContext(),promotions);
            if (isPromoteSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
            //分割线
//            boolean isGradualSuccess = mAdapterGroup.homeDataToGradualZoneAdapter(getContext());
//            if (isGradualSuccess && mViewHelper != null) {
//                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
//            }
        }
    }

    @Override
    public void refreshHomeDataToFirstPorcelains(List<BannerNewItemBean> firstPorcelains) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToFirstPorcelainsAdapter(getContext(),firstPorcelains);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToSecondLive(List<BannerNewItemBean> secondLives) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToSecondLiveOneAdAdapter(getContext(),secondLives);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToThreePorcelains(List<BannerNewItemBean> threePorcelains) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToThreePorcelainAdapter(getContext(),threePorcelains);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToFourthLive(List<BannerNewItemBean> fourthPorcelains) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToFourthLiveTwoAdAdapter(getContext(),fourthPorcelains);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToFirstSale(List<FlashSaleTabBean> tabBeanList) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToSaleTabAdapter(getContext(),tabBeanList);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToSelSale(List<FlashSaleTabBean>flashSaleTabBeans, int selIndex,String status) {
        if (mAdapterGroup != null) {
            mAdapterGroup.homeDataToRefreshSaleTabAdapter(flashSaleTabBeans,selIndex,status);
        }
    }

    @Override
    public void refreshHomeDataToAllSelSale(List<FlashSaleTabBean> flashSaleTabBeans) {
        if (mAdapterGroup != null) {
            mAdapterGroup.homeDataToRefreshSaleTabAdapter(flashSaleTabBeans);
        }
    }

    @Override
    public void refreshHomeDataToTemplateCms(String brand_list_url,List<HomeNewCmsIndexBean> templateCmsData) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToTemplateCmsAdapter(getContext(),brand_list_url,templateCmsData);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToSpecialCms(HomeCmsIndexBean specialCmsData) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToSpecialCmsAdapter(getContext(),specialCmsData);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshHomeDataToFooterTab(HomeFooterTabData footerTabBeans, String footerTabSwitch) {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataToFooterClassAdapter(getContext(),null);
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }

    @Override
    public void refreshFooterTiltle() {
        if (mAdapterGroup != null) {
            boolean isSuccess = mAdapterGroup.homeDataFooterTitle(getContext());
            if (isSuccess && mViewHelper != null) {
                mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
            }
        }
    }


    //TODO:刷新底部
    @Override
    public void refreshHomeFirstLoadFooterShopList(List<HomeFooterTabBean> footerTabBeans) {
        if (mAdapterGroup != null) {
            mAdapterGroup.homeDataToFooterShopList(getContext(),footerTabBeans);
        }
    }

    @Override
    public void loadMoreHomeDataToFooterShopList(int index,List<ProductHomeMessage> productMessageList) {

        if (mAdapterGroup != null) {
            if (mAdapterGroup.getHomePageFooterAdapter() == null || iHomePresenter.getCurrentPage() == 1){
                boolean isSuccess = mAdapterGroup.homeDataToFooterClassAdapter(getContext(),productMessageList);
                if (isSuccess && mViewHelper != null) {
                    mViewHelper.setFooterStickPosition(mViewHelper.getFooterStickPosition()+1);
                }
                mAdapterGroup.homeDataToRefreshEnd();
            } else {
                mAdapterGroup.homeDataToLoadMoreShopList(getContext(),index,productMessageList);
            }
        }
    }

    /**
     * 首页接口处理完成
     * */
    @Override
    public void refreshHomeDataToEnd() {
        if (mAdapterGroup != null) {
            mAdapterGroup.homeDataToRefreshEnd();
        }
    }

}
